package com.yirui.serialcomm.core;

import com.yirui.serialcomm.core.parse.PacketParser;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

/**
 * MC数据包遍历处理器实现
 *
 * @author Dujie
 * @create 2025/8/12
 * @since 1.0.0
 */
public class MCChunkIterator<T> implements Iterator, Closeable {
    private boolean hasNextChunk = false;
    private final InputStream inputStream;
    private PacketParser packetParser;
    public MCChunkIterator(InputStream inputStream, PacketParser packetParser) {
        this.inputStream = inputStream;
        this.packetParser = packetParser;
    }

    @Override
    public void close() throws IOException {
        inputStream.close();
        packetParser = null;
    }

    @Override
    public boolean hasNext() {
        hasNextChunk = packetParser.matchHeader(inputStream);
        return hasNextChunk;
    }

    @Override
    public T next() {
        try {
            return packetParser.decode(inputStream);
        } catch (IOException e) {
            hasNextChunk = false;
            throw new RuntimeException("Failed to read MC chunk", e);
        }
    }






    public void setParser(PacketParser packetParser) {
        this.packetParser = packetParser;
    }
}
